package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.domain.SysBmType;
import com.ruoyi.system.domain.vo.SysBmTypeExcelVO;
import com.ruoyi.system.service.ISysBmTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 编码配置Controller
 *
 * @author yy
 * @date 2021-11-19
 */
@Api(tags = "设备编码配置")
@RestController
@RequestMapping("/sysBmType")
public class SysBmTypeController extends BaseController {
    @Autowired
    private ISysBmTypeService sysBmTypeService;

    /**
     * 查询编码配置列表
     */
    @ApiOperation(value = "查询编码配置列表", notes = "查询编码配置列表")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:list")
    @GetMapping("/list")
    public AjaxResult list(SysBmType sysBmType) {
        List<SysBmType> list = sysBmTypeService.selectSysBmTypeList(sysBmType);
        return AjaxResult.success(list);
    }

    /**
     * 导出编码配置列表
     */
    @ApiOperation(value = "导出编码配置列表", notes = "导出编码配置列表")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:export")
    @Log(title = "编码配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBmType sysBmType) throws IOException {
        List<SysBmType> list = sysBmTypeService.selectSysBmTypeList(sysBmType);
        ExcelUtil<SysBmType> util = new ExcelUtil<SysBmType>(SysBmType.class);
        util.exportExcel(response, list, "编码配置数据");
    }

    /**
     * 获取编码配置详细信息
     */
    @ApiOperation(value = "获取编码配置详细信息", notes = "获取编码配置详细信息")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:query")
    @GetMapping(value = "/{bmId}")
    public AjaxResult getInfo(@PathVariable("bmId") Long bmId) {
        return AjaxResult.success(sysBmTypeService.selectSysBmTypeById(bmId));
    }

    /**
     * 新增编码配置
     */
    @ApiOperation(value = "新增编码配置", notes = "新增编码配置")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:add")
    @Log(title = "编码配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBmType sysBmType) {
        return toAjax(sysBmTypeService.insertSysBmType(sysBmType));
    }

    /**
     * 修改编码配置
     */
    @ApiOperation(value = "修改编码配置", notes = "修改编码配置")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:edit")
    @Log(title = "编码配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody List<SysBmType> sysBmTypes) {
        for (SysBmType sysBmType:sysBmTypes){
            sysBmTypeService.updateSysBmType(sysBmType);
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除编码配置
     */
    @ApiOperation(value = "删除编码配置", notes = "删除编码配置")
    @ApiImplicitParam(name = "ids", value = "编码配置ID数组", required = true, paramType = "path", allowMultiple = true, dataType = "String")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:remove")
    @Log(title = "编码配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{bmIds}")
    public AjaxResult remove(@PathVariable Long[] bmIds) {
        return toAjax(sysBmTypeService.deleteSysBmTypeByIds(bmIds));
    }

    /**
     * 导入抄表记录列表,
     */
    @ApiOperation(value = "导入抄表记录", notes = "导入抄表记录")
    @PreAuthorize(hasPermi = "sysBmType:sysBmType:import")
    @Log(title = "导入抄表记录", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {

        ExcelUtil<SysBmTypeExcelVO> util = new ExcelUtil<SysBmTypeExcelVO>(SysBmTypeExcelVO.class);
        List<SysBmTypeExcelVO> sysBmTypeExcelVOS = util.importExcel(file.getInputStream());
        //批量插入数据
        sysBmTypeExcelVOS = sysBmTypeExcelVOS.stream().filter(o -> StringUtils.isNotBlank(o.getParkCode())).collect(Collectors.toList());

        Map<String, List<SysBmTypeExcelVO>> listMap = sysBmTypeExcelVOS.stream().collect(Collectors.groupingBy(SysBmTypeExcelVO::getParkName));


        for (Map.Entry<String, List<SysBmTypeExcelVO>> entry : listMap.entrySet()) {
            // 判断园区是否存在
            String parkName = entry.getKey();
            String parkCode = entry.getValue().get(0).getParkCode();
            SysBmType q1 = new SysBmType();
            q1.setName(parkName);
            q1.setValue(parkCode);
            q1.setParentId(0L);
            List<SysBmType> l1 = sysBmTypeService.selectSysBmTypeList(q1);
            Long parentId = 0L;
            if (l1.size() == 0) {
                q1.setLv(1);
                q1.setCode("1");
                q1.setParentId(0L);
                q1.setGenCode(parkCode);
                q1.setHierarchy(parkName);
                sysBmTypeService.insertSysBmType(q1);
                parentId = q1.getBmId();
            }
            Map<String, List<SysBmTypeExcelVO>> deviceSystem = entry.getValue().stream().collect(Collectors.groupingBy(SysBmTypeExcelVO::getDeviceSystem));

            for (Map.Entry<String, List<SysBmTypeExcelVO>> systemEntry : deviceSystem.entrySet()) {
                String deviceSystemName = systemEntry.getKey();
                String deviceSystemCode = systemEntry.getValue().get(0).getDeviceSystemCode();
                SysBmType q2 = new SysBmType();
                q2.setName(deviceSystemName);
                q2.setValue(deviceSystemCode);
                q2.setParentId(parentId);
                List<SysBmType> l2 = sysBmTypeService.selectSysBmTypeList(q2);
                long deviceSystemParent = 0L;
                if (l2.size() == 0) {
                    q2.setLv(2);
                    q2.setCode("1");
                    q2.setParentId(parentId);
                    q2.setGenCode(parkCode + "-" + deviceSystemCode);
                    q2.setHierarchy(parkName + "-" + deviceSystemName);
                    sysBmTypeService.insertSysBmType(q2);
                    deviceSystemParent = q2.getBmId();
                }

                Map<String, List<SysBmTypeExcelVO>> deviceChilds = systemEntry.getValue().stream().collect(Collectors.groupingBy(SysBmTypeExcelVO::getDeviceChildName));

                for (Map.Entry<String, List<SysBmTypeExcelVO>> deviceChild : deviceChilds.entrySet()) {

                    String deviceChildName = deviceChild.getKey();
                    String deviceChildCode = deviceChild.getValue().get(0).getDeviceChildCode();
                    logger.error("====>" + deviceChildCode + "====>" + deviceChildName + "====>" + deviceSystemParent);
                    logger.error("====>" + deviceChilds.entrySet().toString());
                    SysBmType q3 = new SysBmType();
                    q3.setName(deviceChildName);
                    q3.setValue(deviceChildCode);
                    q3.setParentId(deviceSystemParent);
                    List<SysBmType> l3 = sysBmTypeService.selectSysBmTypeList(q3);
                    long deviceChildParent = 0L;
                    if (l3.size() == 0) {
                        q3.setLv(3);
                        q3.setCode("1");
                        q3.setParentId(deviceSystemParent);
                        q3.setGenCode(parkCode + "-" + deviceSystemCode + "-" + deviceChildCode);
                        q3.setHierarchy(parkName + "-" + deviceSystemName + "-" + deviceChildName);
                        sysBmTypeService.insertSysBmType(q3);
                        deviceChildParent = q3.getBmId();
                    }
                    Map<String, List<SysBmTypeExcelVO>> deviceTypes = deviceChild.getValue().stream().collect(Collectors.groupingBy(SysBmTypeExcelVO::getDeviceType));
                    for (Map.Entry<String, List<SysBmTypeExcelVO>> deviceType : deviceTypes.entrySet()) {
                        String deviceTypeName = deviceType.getKey();
                        String deviceTypeCode = deviceType.getValue().get(0).getDeviceTypeCode();
                        logger.error("******" + deviceTypeName + "******" + deviceTypeCode + "******" + deviceChildParent);
                        logger.error("******" + deviceType.getValue().toString());

                        SysBmType q4 = new SysBmType();
                        q4.setName(deviceTypeName);
                        q4.setValue(deviceTypeCode);
                        q4.setParentId(deviceChildParent);
                        List<SysBmType> l4 = sysBmTypeService.selectSysBmTypeList(q4);
                        long deviceTypeParent = 0L;
                        if (l4.size() == 0) {
                            q4.setLv(4);
                            q4.setCode("1");
                            q4.setParentId(deviceChildParent);
                            q4.setGenCode(parkCode + "-" + deviceSystemCode + "-" + deviceChildCode + "-" + deviceTypeCode);
                            q4.setHierarchy(parkName + "-" + deviceSystemName + "-" + deviceChildName + "-" + deviceTypeName);
                            sysBmTypeService.insertSysBmType(q4);
                            deviceTypeParent = q4.getBmId();
                        }
                    }

                }
            }
        }

        return AjaxResult.success();

    }


}
